package com.openlogic.flow.utils;

import java.util.List;

import org.dromara.warm.flow.core.constant.ExceptionCons;
import org.dromara.warm.flow.core.entity.Node;
import org.dromara.warm.flow.core.enums.NodeType;
import org.dromara.warm.flow.core.enums.SkipType;
import org.dromara.warm.flow.core.service.NodeService;
import org.dromara.warm.flow.core.service.TaskService;
import org.dromara.warm.flow.core.service.UserService;
import org.dromara.warm.flow.core.utils.AssertUtil;
import org.dromara.warm.flow.core.utils.CollUtil;
import org.dromara.warm.flow.orm.entity.FlowNode;
import org.dromara.warm.flow.orm.mapper.FlowNodeMapper;
import org.dromara.warm.flow.orm.mapper.FlowTaskMapper;
import org.noear.solon.Solon;

import com.mybatisflex.core.query.QueryWrapper;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * @ClassName: OpenLogicFLowUtils
 * @Description: 流程工具类
 * @author weiyongpeng
 * @date 2025年2月12日 下午8:32:49
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class OpenLogicFLowUtils {

//	private static final IFlwTaskAssigneeService TASK_ASSIGNEE_SERVICE = Solon.cfg().getBean(IFlwTaskAssigneeService.class);
//    private static final IFlwTaskService FLW_TASK_SERVICE = Solon.cfg().getBean(IFlwTaskService.class);
	private static final FlowNodeMapper FLOW_NODE_MAPPER = Solon.context().getBean(FlowNodeMapper.class);
	private static final FlowTaskMapper FLOW_TASK_MAPPER = Solon.context().getBean(FlowTaskMapper.class);
	private static final UserService USER_SERVICE = Solon.context().getBean(UserService.class);
	private static final TaskService TASK_SERVICE = Solon.context().getBean(TaskService.class);

	private static final NodeService NODE_SERVICE = Solon.context().getBean(NodeService.class);;

	 /**
     * 获取工作流用户service
     */
    public static UserService getFlowUserService() {
        return USER_SERVICE;
    }
	/**
	 * 描述：申请人节点编码
	 * @Title: applyNodeCode
	 * @param definitionId 流程定义id
	 * @return 申请人节点编码
	 * @author weiyongpeng
	 * @date 2025年2月11日 下午7:14:19
	 */
	public static String applyNodeCode(Long definitionId) {
		// 获取已发布的流程节点
		List<FlowNode> flowNodes = FLOW_NODE_MAPPER
				.selectListByQuery(QueryWrapper.create().and(FlowNode::getDefinitionId).eq(definitionId));
		AssertUtil.isTrue(CollUtil.isEmpty(flowNodes), ExceptionCons.NOT_PUBLISH_NODE);
		Node startNode = flowNodes.stream().filter(t -> NodeType.isStart(t.getNodeType())).findFirst().orElse(null);
		AssertUtil.isNull(startNode, ExceptionCons.LOST_START_NODE);
		Node nextNode = NODE_SERVICE.getNextNode(definitionId, startNode.getNodeCode(), null, SkipType.PASS.getKey());
		return nextNode.getNodeCode();
	}
	
}
